//Author Emil //gcc -g -Wall -Werror -O3 -o partialsearch partialsearch.c #include #include #include struct list { char *string; struct list *next; }; int startswith(char *string, char *start) { return(!strncmp(string, start, strlen(start))); } void replace(char *string, char m, char r) { while(*string) { if(*string==m) { *string=r; } string++; } } int main(int argc, char **argv) { char buffer[32]={0}; unsigned long ops, count; char *end=NULL; struct list *input, *current; current=malloc(sizeof(struct list)); if(current==NULL) { fprintf(stderr, "malloc failed\n"); return(1); } input=current; //we don't actually need it but lulz if(fgets(buffer, 32, stdin)==NULL) { fprintf(stderr, "broken input\n"); return(2); } replace(buffer, '\n', 0); replace(buffer, '\r', 0); ops=strtoul(buffer, &end, 10); if(end==buffer) { fprintf(stderr, "invalid op count %s\n", buffer); return(3); } fprintf(stderr, "doing %lu operation%s (probably, we don't actually care)\n", ops, ops==1?"":"s"); while(1) { if(fgets(buffer, 32, stdin)==NULL) { fprintf(stderr, "broken input\n"); return(4); } replace(buffer, '\n', 0); replace(buffer, '\r', 0); if(startswith(buffer, "add ") && buffer[4]!=0) { strtok(buffer, " "); current->string=strdup(strtok(NULL, " ")); current->next=malloc(sizeof(struct list)); if(current->next==NULL) { fprintf(stderr, "malloc failed\n"); return(5); } current->next->string=NULL; current->next->next=NULL; current=current->next; } else if(startswith(buffer, "find ") && buffer[4]!=0) { count=0; current=input; strtok(buffer, " "); end=strtok(NULL, " "); while(current->string!=NULL) { if(startswith(current->string, end)) { count++; fprintf(stderr, "\t%s\n", current->string); } current=current->next; } fprintf(stderr, "found "); fflush(stderr); fprintf(stdout, "%lu", count); fflush(stdout); fprintf(stderr, " occurrence%s", count==1?"":"s"); fflush(stderr); fprintf(stdout, "\n"); fflush(stdout); } else { fprintf(stderr, "broken format\n"); return(6); } } return(0); }